
const rootCode = '40000012212'

let delayIndex = 0;
let wzIndex = 1
console.time('total')
const forFetch = (urls, index = 0, result = [], options = [], callback, delay = 0, count = 8, delayGap = 30000) => {
    if (delay !== 0) {
        if (delayIndex > count) {
            delayIndex = 0;
            delay = delayGap
        } else {
            delay = 1;
        }
    }
    setTimeout(() => {
        const url = urls[index];
        const option = options[index] || {};
        if (!url) {
            callback(result)
            return;
        }
        fetch(url, {
            headers: {
                "Content-Type": "application/json"
            },
            ...option
        }).then(resp => {
            return resp.json();
        }).then(resp => {
            if (delay !== 0) {
                delayIndex++;
            }
            result.push(resp);
            if (urls.length > index) {
                forFetch(urls, ++index, result, options, callback, delay, count, delayGap);
            } else {
                callback(result);
            }
        }).catch(err => {
            if (urls.length > index) {
                forFetch(urls, ++index, result, options, callback, delay, count, delayGap);
            } else {
                callback(result);
            }
        })
    }, delay);
}
const fts = [] // 发帖
Promise.all([fetch(`/api/courses/${rootCode}/modules`).then(resp => {
    return resp.json()
}),
fetch(`/api/course/${rootCode}/online-video-completeness/setting?no-loading-animation=true`),
fetch(`/api/courses/${rootCode}?fields=id,name,start_date,end_date,course_code,subject_code,credit,is_child,is_master,has_instruction_team,course_attributes(student_count,teaching_class_name,data),academic_year,semester,public_scope,learning_mode,teaching_mode,score_published,students_count,compulsory,syllabus_enabled,imported_from,course_type,audit_status,display_name,classroom_schedule,second_name,department(id,code,name),grade(id,name),klass(id,name),instructors(id,user_no,email,avatar_big_url,avatar_small_url,name,portfolio_url),org(is_enterprise_or_organization,is_transfer_arrears)`).then(resp3 => {
    return resp3.json();
}),
fetch(`/api/course/${rootCode}/activity-reads-for-user`).then(r6 => {
    return r6.json()
})]).then(resps => {
    const [resp, a, resp3, resp6] = resps;
    const modules = resp.modules
    // modules.shift()
    // modules.shift()
    // modules.shift()
    // modules.shift()
    // modules.shift()
    // modules.shift()
    // modules.shift()
    forFetch(modules.map(m => {
        return `/api/course/${rootCode}/all-activities?module_ids=[${m.id}]&activity_types=learning_activities,exams,classrooms,live_records,rollcalls&no-loading-animation=true`
    }), 0, [], {}, resp2s => {
        const learning_activities = [];
        resp2s.forEach((resp2, i) => {
            learning_activities.push(...(resp2?.learning_activities || []))
        })
        const items = [];
        learning_activities?.filter(item => {
            const comItem = resp6.activity_reads?.find(r => {
                return r.activity_id === item.id && r.completeness === 'full'
            })
            if (comItem) {
                return false;
            }
            return true
        }).forEach((item, i) => {
            // items.push({
            //     url: `/api/course/${rootCode}/activity-reads-for-user`
            // })
            // items.push({
            //     url: `/api/courses/${rootCode}/teaching-team/orgs`
            // })

            if (item.completion_criterion === '参与发帖或回帖' || !item.completion_criterion) {
                fts.push(item)
            } else {
                items.push({
                    url: `/api/course/activities-read/${item.id}`,
                    options: {
                        method: 'post'
                    }
                })
                item.uploads?.forEach(upload => {
                    if (upload?.videos?.length === 0 && upload.reference_id) {
                        items.push({
                            url: `/api/course/activities-read/${item.id}`,
                            options: {
                                method: 'post',
                                body: JSON.stringify({
                                    upload_id: upload.id
                                }),
                                headers: {
                                    "Content-Type": "application/json"
                                }
                            }
                        })
                        // items.push({
                        //     url: `/api/uploads/reference/document/${upload.reference_id}/url?preview=true`
                        // })
                    }
                    upload?.videos?.forEach(video => {
                        const now = new Date().valueOf();
                        const duration = parseInt(video?.duration);
                        const startDate = now;
                        // items.push({
                        //     url: `/statistics/api/learning-activity`,
                        //     options: {
                        //         method: 'post',
                        //         body: JSON.stringify({
                        //             action: "open",
                        //             activity_id: item.id,
                        //             activity_name: null,
                        //             activity_type: "online_video",
                        //             channel: "web",
                        //             course_code: resp3.course_code,
                        //             course_id: resp3.id,
                        //             course_name: resp3.name,
                        //             dep_code: "5100500",
                        //             dep_id: "40000000086",
                        //             dep_name: "绵阳广播电视大学直属部",
                        //             enrollment_role: "student",
                        //             is_teacher: false,
                        //             master_course_id: 43726,
                        //             mode: "normal",
                        //             module: null,
                        //             org_code: "510",
                        //             org_id: 40000000001,
                        //             org_name: "四川开放大学",
                        //             sub_id: upload.id,
                        //             sub_type: "mp4",
                        //             target_info: {},
                        //             ts: startDate,
                        //             user_agent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.43",
            
                        //             user_name,
                        //             user_no,
                        //         })
                        //     }
                        // })
                        // items.push({
                        //     url: `/api/notes?course_id=${rootCode}&activity_id=${item.id}&target_id=${upload.id}`
                        // })
                        // items.push({
                        //     url: `/api/uploads/${upload.id}?preview=true`
                        // })

                        if (duration) {
                            for (let i = 0; i < duration / 60; i++) {
                                const start = i * 60
                                const end = Math.min(i * 60 + 60, duration)
                                items.push({
                                    url: `/api/course/activities-read/${item.id}`,
                                    options: {
                                        method: 'post',
                                        body: JSON.stringify({
                                            start,
                                            end
                                        }),
                                        headers: {
                                            "Content-Type": "application/json"
                                        }
                                    }
                                })
                            }
                        }
                    })
                })

            }

        })
        forFetch(items.map(item => {
            return item.url;
        }), 0, [], items.map(item => {
            return item.options
        }), () => {
            if (fts.length > 0) {
                forFetch(fts.map(item => {
                    return `/api/forum/${item.id}/category?fields=id,title,activity(id,sort,module_id,syllabus_id,start_time,end_time,is_started,is_closed,data,can_show_score,score_percentage,title,prerequisites,submit_by_group,group_set_id,group_set_name,imported_from,parent_id),referrer_type`
                }), 0, [], [], rs => {
                    forFetch(rs.map(r => {
                        return `/api/topics`
                    }), 0, [], rs.map(r => {
                        const date = new Date()
                        return {
                            method: 'post',
                            headers: {
                                "Content-Type": "application/json"
                            },
                            body: JSON.stringify({
                                "title": "认真学习",
                                "content": `<p>我要认真学习，努力学习，天天向上，加油,<div style="display:none">${Math.random().toString()}</div></p>`,
                                "uploads": [],
                                "category_id": r?.topic_category?.id
                            })
                        }
                    }), () => {
                        console.timeEnd('total')
                    }, 2000, 1, 60000)
                }, 0)
                // fetch(`/api/forum/${item.id}/category?fields=id,title,activity(id,sort,module_id,syllabus_id,start_time,end_time,is_started,is_closed,data,can_show_score,score_percentage,title,prerequisites,submit_by_group,group_set_id,group_set_name,imported_from,parent_id),referrer_type`).then(resp5 => {
                //     return resp5.json()
                // }).then(resp5 => {

                //     resp5?.topic_category?.id && fetch(`/api/topics`, {
                //         method: 'post',
                //         headers: {
                //             "Content-Type": "application/json"
                //         },
                //         body: JSON.stringify({
                //             "title": "认真学习",
                //             "content": "<p>我要认真学习</p>",
                //             "uploads": [],
                //             "category_id": resp5?.topic_category?.id
                //         })
                //     })
                // })
            } else {

                console.timeEnd('total')
            }
        }, 2000)
    })
})
